package com.lemon.smartsafetynew.ui.activity.ledger;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.BaseActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.KeyBoardUtils;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.entity.common.DateTypeEnum;
import com.lemon.smartsafetynew.entity.ledger.LedgerStatisticsVo;
import com.lemon.smartsafetynew.net.services.SafeLedgerServices;
import com.lemon.smartsafetynew.ui.widget.ProgressArcView;
import com.lemon.smartsafetynew.ui.widget.marker.MyMarkerView;
import com.lemon.smartsafetynew.util.common.ColorUtil;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.common.StringResUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Andrew on 2017/8/14.
 */

public class LedgerPatrolDetailActivity extends BaseActivity {

    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.spinner)
    ImageView spinner;  //TODO add animation at feature
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.report_type_layout)
    LinearLayout reportTypeLayout;

    @Bind(R.id.index_last)
    ImageView indexLast;
    @Bind(R.id.time_tv)
    TextView timeTv;
    @Bind(R.id.index_next)
    ImageView indexNext;

    @Bind(R.id.left_progress)
    ProgressArcView leftProgress;
    @Bind(R.id.left_one)
    TextView leftOne;
    @Bind(R.id.left_two)
    TextView leftTwo;
    @Bind(R.id.left_three)
    TextView leftThree;

    @Bind(R.id.center_progress)
    ProgressArcView centerProgress;
    @Bind(R.id.center_one)
    TextView centerOne;
    @Bind(R.id.center_two)
    TextView centerTwo;
    @Bind(R.id.center_three)
    TextView centerThree;

    @Bind(R.id.right_one)
    TextView rightOne;
    @Bind(R.id.right_two)
    TextView rightTwo;

    @Bind(R.id.dash_bord_layout)
    LinearLayout dashBordLayout;
    @Bind(R.id.more_layout)
    LinearLayout moreLayout;
    @Bind(R.id.chart_description_tv)
    TextView chartDescriptionTv;
    @Bind(R.id.line_chart)
    LineChart lineChart;

    @Bind(R.id.patrol_time_tv)
    TextView patrolTimeTv;
    @Bind(R.id.patrol_person_tv)
    TextView patrolPersonTv;

    private int type = 1;                               // 1: 安全巡查   2：安全隐患  3: 动态监测
    private DateTypeEnum date_type = DateTypeEnum.DAY;  //default is day

    private Date date;
    private Date currentDate;
    private User user;

    @Override
    protected void getBundleArgs() {

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            type = bundle.getInt(KeyConstants.KEY_LEDGER_DATA_TYPE);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_ledger_patrol_detail;
    }

    @Override
    protected void initViews() {

        //  ====== value =======
        initData();

        // ===== UI ======
        initToolbar();
        initDashBoardView();
        initLineChart();

        requestNetData(type);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        OkHttpUtils.getInstance().cancelTag(KeyConstants.URL_GET_SAFE_LEDGER_STATISTICS_OF_SAFE_PATROL_MORE);
    }

    private void initToolbar() {

        toolbar.setTitle("");
        toolbar.setContentInsetsAbsolute(0, 0);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtils.closeSoftInput(LedgerPatrolDetailActivity.this);
                callFinish();
            }
        });

        // ==== set title value =====
        mainTitle.setText("" + getString(StringResUtil.ledgerBannerString[type]) + "日报");

    }


    private void initDashBoardView() {

        //dashBordLayout.setBackgroundColor(Color.parseColor(ColorUtil.ledgerItemColor[type]));

        timeTv.setText(CommonUtil.getNowTimeStr(date_type));
        if (CommonUtil.compareDate(date, currentDate)) {
            indexNext.setVisibility(View.VISIBLE);
        } else {
            indexNext.setVisibility(View.INVISIBLE);
        }

    }

    private void initData() {

        date = CommonUtil.getNowDate();
        currentDate = date;

        user = AccountUtil.getUser();
        if (user == null) {
            Toast.makeText(LedgerPatrolDetailActivity.this, "用户不存在", Toast.LENGTH_LONG).show();
        }
    }

    private void requestNetData(int type) {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("company_id", user.getCompanyId());
        params.put("type", date_type.getName().toLowerCase()); //这里只需要Day
        params.put("date", timeTv.getText().toString().trim());
        params.put("moreInfo", 1);

        switch (type) {
            case 1: // 安全巡查
                SafeLedgerServices.init().getSafePatrolMoreDetailData(params);
                break;
            case 2: // 安全隐患

                break;
            case 3: // 动态监测
                break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GET_SAFE_LEDGER_STATISTICS_OF_SAFE_PATROL_MORE.equals(event.getTag())) {

            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    LedgerStatisticsVo statisticsVo = (LedgerStatisticsVo) event.getObj();
                    initContentView(statisticsVo);
                    showLineChartData(statisticsVo.getData_map());

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }
        }
    }

    private void initContentView(LedgerStatisticsVo statisticsVo) {

        leftProgress.setProgress(statisticsVo.getItem_total_num(), statisticsVo.getItem_checked_num());
        leftOne.setText("总巡查点：" + statisticsVo.getItem_total_num());
        leftTwo.setText("已巡查点：" + statisticsVo.getItem_checked_num());
        leftThree.setText("未巡查点：" + (statisticsVo.getItem_total_num() - statisticsVo.getItem_checked_num()));

        centerProgress.setProgress(statisticsVo.getTask_total_num(), statisticsVo.getTask_done_num());
        centerOne.setText("全部任务：" + statisticsVo.getTask_total_num());
        centerTwo.setText("已执行任务：" + statisticsVo.getTask_done_num());
        centerThree.setText("未执行任务：" + (statisticsVo.getTask_to_do_num()
                + statisticsVo.getTask_doing_num() + statisticsVo.getTask_over_time_num()));

        rightOne.setText("" + statisticsVo.getRed_num());

        patrolTimeTv.setText(CommonUtil.formatTime(statisticsVo.getTask_total_hour_num()));
        patrolPersonTv.setText(statisticsVo.getTask_user_num() + "人");

    }


    // ======== LineChart ========
    private void initLineChart() {

        lineChart.setDrawGridBackground(false);
        lineChart.setNoDataText("无数据");
        // no description text
        lineChart.getDescription().setEnabled(false);

        // enable touch gestures
        lineChart.setTouchEnabled(true);

        // enable scaling and dragging
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(false);
        lineChart.setScaleXEnabled(true);
        lineChart.setDoubleTapToZoomEnabled(false);
        // mChart.setScaleYEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(false);

        lineChart.fitScreen();

        // set an alternative background color
        // mChart.setBackgroundColor(Color.GRAY);

        // create a custom MarkerView (extend MarkerView) and specify the layout
        // to use for it
        //TODO MarkView
        MyMarkerView mv = new MyMarkerView(LedgerPatrolDetailActivity.this, R.layout.custom_marker_view);
        mv.setChartView(lineChart); // For bounds control
        lineChart.setMarker(mv); // Set the marker to the chart

//        XAxis xAxis = lineChart.getXAxis();
//        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//        xAxis.setAxisMinimum(0f);
//        xAxis.setValueFormatter(new IAxisValueFormatter() {
//            @Override
//            public String getFormattedValue(float value, AxisBase axis) {
//                //if(value % 1 != 0) {
//                //   return "";
//                //} else {
//                    return String.valueOf((int)value);
//                //}
//            }
//        });
//        xAxis.setAvoidFirstLastClipping(true);
//        xAxis.setGranularity(1f);

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawZeroLine(false);
        leftAxis.setDrawGridLines(false);

        // limit lines are drawn behind data (and not on top)
        //leftAxis.setDrawLimitLinesBehindData(true);
        lineChart.getAxisRight().setEnabled(false);

        // add data
        //setLineChartData(24, 1000);

        lineChart.setVisibleXRangeMaximum(6.2f);
        //lineChart.setVisibleXRangeMinimum(0);
        lineChart.animateX(500);
        //mChart.invalidate();

        // get the legend (only possible after setting data)
        Legend l = lineChart.getLegend();
        l.setEnabled(false);

        // // dont forget to refresh the drawing
        lineChart.invalidate();

    }

    /**
     * 小时
     * @param map
     */
    private void showChartDaily(Map<Integer, Integer> map) {

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value + "时");
            }
        });
        xAxis.setAvoidFirstLastClipping(true);
        xAxis.setGranularity(1f);

        ArrayList<Entry> values = new ArrayList<>();

        for (int i = 0; i < map.size(); i++) { //24 小时制
            values.add(new Entry(i, map.get(i)));
        }

        LineDataSet set1;

        set1 = new LineDataSet(values, "DataSet 1");
        set1.setDrawValues(false);

        // set the line to be drawn like this "- - - - - -"
        set1.enableDashedLine(10f, 5f, 0f);
        set1.enableDashedHighlightLine(10f, 5f, 0f);
        set1.setColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setCircleColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setLineWidth(1f);
        set1.setCircleRadius(3f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.setDrawFilled(true);
        set1.setFormLineWidth(1f);
        set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
        set1.setFormSize(15.f);
        set1.setHighLightColor(Color.TRANSPARENT);

        set1.setFillColor(Color.parseColor(ColorUtil.lineChartColor));

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1); // add the datasets

        // create a data object with the datasets
        LineData data = new LineData(dataSets);

        // set data
        lineChart.setData(data);

        lineChart.invalidate();
    }

    /**
     * 月
     * @param map
     */
    private void showChartMonth(Map<Integer, Integer> map) {

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value + "日");
            }
        });
        xAxis.setAvoidFirstLastClipping(true);
        xAxis.setGranularity(1f);

        ArrayList<Entry> values = new ArrayList<>();

        for (int i = 1; i <= map.size(); i++) {
            values.add(new Entry(i, map.get(i)));
        }

        LineDataSet set1;

        set1 = new LineDataSet(values, "DataSet 1");
        set1.setDrawValues(false);

        // set the line to be drawn like this "- - - - - -"
        set1.enableDashedLine(10f, 5f, 0f);
        set1.enableDashedHighlightLine(10f, 5f, 0f);
        set1.setColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setCircleColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setLineWidth(1f);
        set1.setCircleRadius(3f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.setDrawFilled(true);
        set1.setFormLineWidth(1f);
        set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
        set1.setFormSize(15.f);
        set1.setHighLightColor(Color.TRANSPARENT);

        set1.setFillColor(Color.parseColor(ColorUtil.lineChartColor));

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1); // add the datasets

        // create a data object with the datasets
        LineData data = new LineData(dataSets);

        // set data
        lineChart.setData(data);

        lineChart.invalidate();
    }

    /**
     * 年
     * @param map
     */
    private void showChartYear(Map<Integer, Integer> map) {

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value + "月");
            }
        });
        xAxis.setAvoidFirstLastClipping(true);
        xAxis.setGranularity(1f);

        ArrayList<Entry> values = new ArrayList<>();

        for (int i = 1; i <= map.size(); i++) {
            values.add(new Entry(i, map.get(i)));
        }

        LineDataSet set1;

        set1 = new LineDataSet(values, "DataSet 1");
        set1.setDrawValues(false);

        // set the line to be drawn like this "- - - - - -"
        set1.enableDashedLine(10f, 5f, 0f);
        set1.enableDashedHighlightLine(10f, 5f, 0f);
        set1.setColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setCircleColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setLineWidth(1f);
        set1.setCircleRadius(3f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.setDrawFilled(true);
        set1.setFormLineWidth(1f);
        set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
        set1.setFormSize(15.f);
        set1.setHighLightColor(Color.TRANSPARENT);

        set1.setFillColor(Color.parseColor(ColorUtil.lineChartColor));

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1); // add the datasets

        // create a data object with the datasets
        LineData data = new LineData(dataSets);

        // set data
        lineChart.setData(data);

        lineChart.invalidate();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }


    @OnClick({R.id.report_type_layout, R.id.index_last, R.id.index_next, R.id.more_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.report_type_layout:
                showPopupWindow(spinner);
                break;
            case R.id.index_last:
                leftArrowBtnClick();
                break;
            case R.id.index_next:
                rightArrowBtnClick();
                break;
            case R.id.more_layout:
                UIHelper.showActivity(LedgerPatrolDetailActivity.this, LedgerPatrolStatisticsActivity.class);
                break;
        }
    }

    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(LedgerPatrolDetailActivity.this).inflate(
                R.layout.popup_report_layout, null);
        // 设置按钮的点击事件
        TextView dayTv = (TextView) contentView.findViewById(R.id.day_report_tv);
        TextView monthTv = (TextView) contentView.findViewById(R.id.month_report_tv);
        TextView yearTv = (TextView) contentView.findViewById(R.id.year_report_tv);

        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        // 设置好参数之后再show
        popupWindow.showAsDropDown(view, -1 * CommonUtil.convertDipOrPx(this, 70), 20);


        dayTv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mainTitle.setText("" + getString(StringResUtil.ledgerBannerString[type]) + ((TextView) v).getText().toString());
                date_type = DateTypeEnum.DAY;
                popupWindow.dismiss();

                reportTypeChange();
            }
        });

        monthTv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mainTitle.setText("" + getString(StringResUtil.ledgerBannerString[type]) + ((TextView) v).getText().toString());
                date_type = DateTypeEnum.MONTH;
                popupWindow.dismiss();

                reportTypeChange();
            }
        });

        yearTv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mainTitle.setText("" + getString(StringResUtil.ledgerBannerString[type]) + ((TextView) v).getText().toString());
                date_type = DateTypeEnum.YEAR;
                popupWindow.dismiss();

                reportTypeChange();
            }
        });

    }


    private void requestData(Date mDate) {

        //========== UI change =======
        timeTv.setText(CommonUtil.dateToTimeStr(mDate, date_type));
        if (CommonUtil.compareDate(mDate, currentDate)) {
            indexNext.setVisibility(View.VISIBLE);
        } else {
            indexNext.setVisibility(View.INVISIBLE);
        }

        //========== http request =======
        //TODO
        getNetData(date_type);
    }

    /**
     * 报表时间周期发生改变,
     */
    private void reportTypeChange() {
        date = CommonUtil.getNowDate();
        requestData(date);
    }

    private void leftArrowBtnClick() {
        date = CommonUtil.calendarDelOne(date_type, date);
        requestData(date);
    }

    private void rightArrowBtnClick() {
        date = CommonUtil.calendarPlusOne(date_type, date);
        requestData(date);
    }

    private void getNetData(DateTypeEnum date_type) {
        switch (date_type) {
            case DAY:   //day
                requestNetData(type);
                break;
            case MONTH: //month
                requestNetData(type);
                break;
            case YEAR:  //year
                requestNetData(type);
                break;
            default:
                break;
        }
    }

    private void showLineChartData(Map<Integer, Integer> map) {
        switch (date_type) {
            case DAY:   //day
                showChartDaily(map);
                break;
            case MONTH: //month
                showChartMonth(map);
                break;
            case YEAR:  //year
                showChartYear(map);
                break;
            default:
                break;
        }
    }

    private void callFinish() {
        AppManager.getAppManager().finishActivity(this);
    }


}
